#!/usr/bin/python

from __future__ import division
import re
import csv
import numpy
import sys, getopt


# Example: python micro.py input.csv output.csv

file=open(sys.argv[1], "r")
ofile=open(sys.argv[2], "wb")
ofile.write("Input file: " + sys.argv[1] + "\n\n")

#os.chdir("/mydir")
#for file in glob.glob("*.txt"):


for index, item in enumerate(file, start=0):   # default is zero

#	print(index, item)
	a = re.search("(End with evaluating partition (\d))", item)
	if a:		
		stop = index
		start = index - 29
		xfile=open(sys.argv[2] + int(n.groups()[1], "wb")
		xfile.write("Input file: " + sys.argv[1] + "\n")
		xfile.write("Partition: " + int(n.groups()[1] + "\n")
		for indx, itm in enumerate(file, start=start, end=stop):
			xfile.write(itm)
		xfile.close()		


trueLabel = 0
correct = 0
predict = 0

for line in file:

	m = re.search("(FAC.*trueLabel_size is:(.*))", line)
	n = re.search("(GPE.*trueLabel_size is:(.*))", line)
	if m:
		trueLabel += int(m.groups()[1])
		ofile.write(m.groups()[0] + "\n")
		
	if n:
		trueLabel += int(n.groups()[1])
		ofile.write(n.groups()[0] + "\n") 

	z = re.search("(FAC.*correct_size is:(.*))", line)
	x = re.search("(GPE.*correct_size is:(.*))", line)
	if z:
		correct += int(z.groups()[1])
		ofile.write(z.groups()[0] + "\n")
	if x:
		correct += int(x.groups()[1])
		ofile.write(x.groups()[0] + "\n")

	y = re.search("(FAC.*predict_size is:(.*))", line)
	j = re.search("(GPE.*predict_size is:(.*))", line)
	if y:
		predict += int(y.groups()[1])
		ofile.write(y.groups()[0] + "\n")
	if j:
		predict += int(j.groups()[1])
		ofile.write(j.groups()[0] + "\n")


ofile.write("truelabels: " + str(trueLabel) + "\n")
ofile.write("correct: " +  str(correct) + "\n")
ofile.write("predict: " + str(predict) + "\n")
print "truelabels: ", trueLabel
print "correct: ", correct
print "predict: ", predict 

fp = 0
fn = 0
precision = 0.0
recall = 0.0
f1 = 0.0

fp = predict - correct 
fn = trueLabel - correct
ofile.write("fp: " + str(fp) + "\n")
ofile.write("fn: " + str(fp) + "\n")

## Precision
precision = correct / (correct + fp)
ofile.write("precision: " + str(precision) + "\n")
print "precision: ", precision

### Recall 
recall = correct / (correct + fn)
ofile.write("recall: " + str(recall) + "\n")
print "recall: ", recall

### F1
f1 = 2 * ((precision*recall)/(precision + recall))
ofile.write("f1: " + str(f1) + "\n")
print "f1: ", f1


file.close()
ofile.close()

print 'Done!'

























